<template>
    <div class="add-first-box">
        <el-button type="success" size="small" title="新增权限组" @click="editRole('add')">
            <el-icon size="18">
                <DocumentAdd />
            </el-icon>
        </el-button>
        <el-button type="primary" size="small" @click="reSearch">查询</el-button>
    </div>
    <div class="second-box">
        <div class="role-box" v-for="(item, index) in rolesInfo" :key="item.ID">
            <div class="title-box">{{ item.ROLENAME }}</div>
            <div class="icon-box">
                <el-button type="warning" size="small" title="分配权限组" @click="editRole('selectChangeAuth', item)">
                    <el-icon size="18">
                        <BrushFilled />
                    </el-icon>
                </el-button>
                <el-button type="warning" size="small" title="分配用户" @click="editRole('selectChangeUser', item)">
                    <el-icon size="18">
                        <User />
                    </el-icon>
                </el-button>
                <el-button type="primary" size="small" title="编辑" @click="editRole('update', item)">
                    <el-icon size="18">
                        <Edit />
                    </el-icon>
                </el-button>
                <el-button type="danger" size="small" title="删除" @click="editSubmit('delete', item)">
                    <el-icon size="18">
                        <RemoveFilled />
                    </el-icon>
                </el-button>
            </div>
        </div>
    </div>
    <Drawer ref="drawerRef" :title="title" :size="size" @cancel-submit="resetForm"
        @submit="editSubmit(submitType, submitData)">
        <el-form :model="rolesObj" ref="updateFormRef" :rules="rules" v-if="!submitType.includes('selectChange')">
            <el-form-item label="ID" :label-width="formLabelWidth">
                <el-input v-model="rolesObj.ID" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="角色" :label-width="formLabelWidth" prop="ROLENAME">
                <el-input v-model="rolesObj.ROLENAME" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="rolesObj.REMARK" autocomplete="off" />
            </el-form-item>
        </el-form>
        <el-checkbox-group v-if="submitType === 'selectChangeAuth'" class="elcb" v-model="checkedAuths"
            @change="handleCheckedAuthsChange">
            <el-checkbox v-for="item in authsInfo" :key="item.ID" :label="item.AUTHORITYNAME" :value="item.ID">
                {{ item.AUTHORITYNAME }}
            </el-checkbox>
        </el-checkbox-group>
        <div class="users-box" v-if="submitType === 'selectChangeUser'">
            <div class="exists-box">
                <!-- <div class="filter-pg-box">
                    <el-select v-model="pgObj.persongroup" clearable placeholder="请选择班组" size="small"
                     @visible-change="changePg" 
                     @change="fliterPg" 
                     @clear="clearPg">
                        <el-option v-for="item in useStore.pgs" :label="item.PGNAME" :value="item.PERSONGROUP"
                            :key="item.PERSONGROUP" />
                    </el-select> 
                </div> -->
                <el-checkbox-group size="small" class="check-btn" v-model="checkedExistsPersons"
                    @change="handleCheckedPersonChange">
                    <el-checkbox-button v-for="item in hasPersonInfo" :key="item.ID" :label="item.USERNAME"
                        :value="item">
                        {{ item.REALNAME }}
                    </el-checkbox-button>
                </el-checkbox-group>
            </div>
            <div class="change-box">
                <el-button type="primary" size="small" title="全部加入" plain :disabled="addUtoRbtnDis"
                    @click="allToHasUsers">
                    <el-icon size="18">
                        <Top />
                    </el-icon>
                </el-button>
                <el-button type="primary" size="small" title="加入" plain :disabled="addAllUtoRbtnDis"
                    @click="toHasUsers">
                    <el-icon size="18">
                        <ArrowUp />
                    </el-icon>
                </el-button>
                <el-button type="warning" size="small" title="移出" plain :disabled="delUtoRbtnDis" @click="toNoHasUsers">
                    <el-icon size="18">
                        <ArrowDown />
                    </el-icon>
                </el-button>
                <el-button type="warning" size="small" title="全部移出" plain :disabled="delAllUtoRbtnDis"
                    @click="allToNoHasUsers">
                    <el-icon size="18">
                        <Bottom />
                    </el-icon>
                </el-button>
            </div>
            <div class="noexists-box">
                <!-- <div class="filter-pg-box">123</div> -->
                <el-checkbox-group size="small" class="check-btn" v-model="checkedNoExistsPersons"
                    @change="handleCheckedNoPersonChange">
                    <el-checkbox-button v-for="item in noHasPersonInfo" :key="item.ID" :label="item.USERNAME"
                        :value="item">
                        {{ item.REALNAME }}
                    </el-checkbox-button>
                </el-checkbox-group>
            </div>
        </div>
    </Drawer>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getRolesInfo, editRoleInfo, hasAuthoritysInfo, changeRole, hasUsersInfo } from '@/utils/adminApi/roles'
import Drawer from '@/components/Drawer.vue'
import { msgOpen } from '@/utils/msg'
import { confirm } from '@/utils/confirm'
import { getAuthoritysInfo } from '@/utils/adminApi/authority'
import { exists, deleteCommonObjectsFromArr2 } from '@/utils/exists'
// import {getPg} from '@/utils/adminApi/usrs'
// import { mainStore } from '@/stores/store'
// import { objCopy } from '@/utils/objCopy'

// const useStore = mainStore()

let rolesInfo = ref([])
let rolesObj = reactive({
    ID: null,
    ROLENAME: "",
    REMARK: ""
})

let drawerRef = ref(null)
let title = ref("")
let size = ref("35%")
let formLabelWidth = ref("80")
let submitType = ref('')

let authsInfo = ref([])
let hasAuthIdArr = ref([])
let submitData = reactive({}) //角色编辑后提交对象
let checkedAuths = ref([]) //已选择的权限组

let hasPersonInfo = ref([])
let noHasPersonInfo = ref([])
let hasPersonIdArr = ref([])  //原始personId数组

let checkedExistsPersons = ref([]) //已选择已加入的用户
let checkedNoExistsPersons = ref([]) //已选择未加入的用户
let submitHasPersonIdArr = ref([])  //提交时personId数组


let addUtoRbtnDis = ref(false)
let addAllUtoRbtnDis = ref(false)
let delUtoRbtnDis = ref(false)
let delAllUtoRbtnDis = ref(false)


//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    ROLENAME: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
    ]
})

/**
 * 权限组选择改变事件
 * @param {Array} val 已勾选数组
 */
const handleCheckedAuthsChange = (val) => {
    // console.log(val);
    checkedAuths.value = val
    submitData = reactive({
        oldAuth: hasAuthIdArr.value,
        newAuth: checkedAuths.value
    })
}

//分配用户按钮状态设置
const allocationBtnStatus = () => {
    if (hasPersonInfo.value.length && noHasPersonInfo.value.length) {
        addUtoRbtnDis.value = false
        addAllUtoRbtnDis.value = false
        delUtoRbtnDis.value = false
        delAllUtoRbtnDis.value = false
    }
    if (!hasPersonInfo.value.length && noHasPersonInfo.value.length) {
        addUtoRbtnDis.value = false
        addAllUtoRbtnDis.value = false
        delUtoRbtnDis.value = true
        delAllUtoRbtnDis.value = true
    }
    if (hasPersonInfo.value.length && !noHasPersonInfo.value.length) {
        addUtoRbtnDis.value = true
        addAllUtoRbtnDis.value = true
        delUtoRbtnDis.value = false
        delAllUtoRbtnDis.value = false
    }
}

/**
 * 过滤须增删的角色用户
 * @param {Array} arr 最终已分配角色用户数组对象
 * @param {Array} oldArr 原始已分配角色用户PERSONID数组
 */
const submitAddDelRoleUsers = (arr, oldArr) => {
    let newHasPersonIdArr = []
    arr.length ? arr.forEach(item => newHasPersonIdArr.push(item.PERSONID)) : []
    let needAdd = exists(newHasPersonIdArr, oldArr)
    // console.log(needAdd)
    let needDel = exists(oldArr, newHasPersonIdArr)
    // console.log(needDel)
    return {
        needAdd,
        needDel
    }
}

/**
 * 已加入角色人员选择
 * @param {Array} val 已勾选数组
 */
const handleCheckedPersonChange = (val) => {
    // console.log(val)     
    checkedExistsPersons.value = val
}

/**
 * 未加入角色人员选择
 * @param {Array} val 已勾选数组
 */
const handleCheckedNoPersonChange = (val) => {
    // console.log(val)
    checkedNoExistsPersons.value = val
}

//角色分配加入用户
const toHasUsers = () => {
    if (!checkedNoExistsPersons.value.length) {
        msgOpen("请选择后再分配")
    } else {
        //加入选择的用户至hasPersonInfo
        checkedNoExistsPersons.value.forEach(item => {
            hasPersonInfo.value.push(item)
        })
        //从noHasPersonInfo减少用户
        noHasPersonInfo.value = deleteCommonObjectsFromArr2(checkedNoExistsPersons.value, noHasPersonInfo.value)
        allocationBtnStatus()
        checkedNoExistsPersons.value = []
        let res = submitAddDelRoleUsers(hasPersonInfo.value, hasPersonIdArr.value)
        submitData = reactive({
            needAdd: res.needAdd,
            needDel: res.needDel
        })
        // console.log(submitData);       
    }
}

//角色移除已分配用户
const toNoHasUsers = () => {
    if (!checkedExistsPersons.value.length) {
        msgOpen("请选择后再分配")
    } else {
        //加入选择的用户至noHasPersonInfo
        checkedExistsPersons.value.forEach(item => {
            noHasPersonInfo.value.push(item)
        })
        //从hasPersonInfo减少用户
        hasPersonInfo.value = deleteCommonObjectsFromArr2(checkedExistsPersons.value, hasPersonInfo.value)
        allocationBtnStatus()
        checkedExistsPersons.value = []
        let res = submitAddDelRoleUsers(hasPersonInfo.value, hasPersonIdArr.value)
        submitData = reactive({
            needAdd: res.needAdd,
            needDel: res.needDel
        })
    }
}

//角色分配加入全部用户
const allToHasUsers = () => {
    if (!noHasPersonInfo.value.length) {
        msgOpen("无需要加入的")
    } else {
        let newHasPersonId = ref([])
        //将noHasPersonInfo加入至hasPersonInfo
        noHasPersonInfo.value.forEach(item => {
            hasPersonInfo.value.push(item)
        })
        //清空noHasPersonInfo用户
        noHasPersonInfo.value = []

        hasPersonInfo.value.forEach((item) => {
            newHasPersonId.value.push(item.PERSONID)
        })
        allocationBtnStatus()
        let res = exists(newHasPersonId.value, hasPersonIdArr.value)
        submitData = reactive({
            needAdd: res,
            needDel: []
        })
    }
}

//角色移除全部已分配用户
const allToNoHasUsers = () => {
    if (!hasPersonInfo.value.length) {
        msgOpen("无需要移除的")
    } else {
        let newHasPersonId = ref([])
        //将hasPersonInfo加入至noHasPersonInfo
        hasPersonInfo.value.forEach(item => {
            noHasPersonInfo.value.push(item)
        })
        //清空hasPersonInfo用户
        hasPersonInfo.value = []

        noHasPersonInfo.value.forEach((item) => {
            newHasPersonId.value.push(item.PERSONID)
        })
        allocationBtnStatus()
        submitData = reactive({
            needAdd: [],
            needDel: newHasPersonId
        })
    }
}

//重新查询
const reSearch = async () => {
    let rolesInfoRes = await getRolesInfo()
    // console.log(authoritysInfoRes)  
    rolesInfo.value = rolesInfoRes.datas.roles
}

//重置权限组对象
const resetForm = () => {
    rolesObj = reactive({
        ID: null,
        ROLENAME: "",
        REMARK: ""
    })
    checkedExistsPersons.value = []
    checkedNoExistsPersons.value = []
    submitHasPersonIdArr.value = []
}


/**
 * 分配权限组/用户
 * @param type 处理类型
 * @param row  行对象
 */
const editRole = async (type, row) => {
    // console.log(type);
    // console.log(row);       
    submitType.value = type
    drawerRef.value.open()
    if (type === "add") {
        title.value = "新增"
        resetForm()
        submitData = rolesObj
    } else if (type === "update") {
        title.value = "编辑"
        rolesObj = row
        submitData = rolesObj
    } else if (type.includes("selectChange")) {
        if (type.includes("Auth")) {
            title.value = "分配角色权限"
            hasAuthIdArr.value = []
            let authRes = await getAuthoritysInfo()
            authsInfo.value = authRes.datas.authoritys
            let hasAuthsRes = await hasAuthoritysInfo(row.ID)
            // console.log(hasAuthsRes);
            hasAuthIdArr.value = hasAuthsRes.datas.hasAuths.map((obj) => obj.AUTHORITYID)
            checkedAuths.value = hasAuthIdArr.value
        } else if (type.includes("User")) {
            title.value = "分配角色用户"
            hasPersonIdArr.value = []
            // pgObj.persongroup = ''
            let userRes = await hasUsersInfo(row.ID)
            // console.log(userRes);
            hasPersonInfo.value = userRes.datas.hasUsers
            noHasPersonInfo.value = userRes.datas.noHasUsers
            // oldHasPersonInfo.value = objCopy(hasPersonInfo.value,oldHasPersonInfo.value) //复制一份，用过滤班组使用
            // oldNoHasPersonInfo.value = objCopy(noHasPersonInfo.value,oldNoHasPersonInfo.value) //复制一份，用过滤班组使用
            // console.log(hasPersonInfo.value)
            // console.log(noHasPersonInfo.value)
            if (hasPersonInfo.value.length) {
                hasPersonInfo.value.forEach(e => {
                    hasPersonIdArr.value.push(e.PERSONID)
                })
            }
            //按钮设置    
            allocationBtnStatus()
        }
    }
}


/**
 * 提交处理
 * @param {String} type 处理类型
 * @param {Object} data 表单对象,selectChange改变权限时对象属性为数组
 */
const editSubmit = async (type, data) => {
    // console.log(type)
    // console.log(data)       
    if (type === 'update' || type === 'add') {
        updateFormRef.value.validate(async (valid) => {
            if (!valid) {
                return false
            } else {
                drawerRef.value.showLoading()
                let newRoles = await editRoleInfo(type, data)
                // console.log(newAuthoritys);
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                msgOpen(newRoles.msg, 'success')
                reSearch()
                resetForm()
            }   
        })
    } else if (type === "delete") {
        let res = await confirm(data.ID)
        if (res) {
            let newRoles = await editRoleInfo(type, data)
            // console.log(newAuthoritys);
            msgOpen(newRoles.msg, 'success')
            reSearch()
        }
    } else if (type === "selectChangeAuth") {
        if (!data.oldAuth || (!data.oldAuth.length && !data.newAuth.length)) {
            msgOpen("未变更权限，无需提交")
        } else {
            drawerRef.value.showLoading()
            let newAuthoritys = await changeRole(type, data)
            // console.log(newAuthoritys);
            drawerRef.value.hideLoading()
            drawerRef.value.close()
            msgOpen(newAuthoritys.msg, 'success')
        }
    } else if (type === "selectChangeUser") {
        if (!data.needAdd.length && !data.needDel.length) {
            msgOpen("未重新分配用户，无需提交")
        } else {
            drawerRef.value.showLoading()
            let newUsers = await changeRole(type, data)
            drawerRef.value.hideLoading()
            drawerRef.value.close()
            msgOpen(newUsers.msg, 'success')
        }

    }
}


//202500721新增，用于筛选班组信息
// let pgObj = reactive({persongroup: '',})
// let oldHasPersonInfo = ref([])
// let oldNoHasPersonInfo = ref([])
// //获取班组信息
// const changePg = async ()=>{  
//     if(!useStore.pgs.length){
//         let pgs = await getPg()
//         useStore.setPgs(pgs.datas.pgs)       
//     }    
// }

// //筛选用户
// const fliterPg = ()=>{
//     if(pgObj.persongroup){
//         hasPersonInfo.value = oldHasPersonInfo.value.filter(item=>item.PERSONGROUP === pgObj.persongroup)
//     }
// }
// //清空筛选条件
// const clearPg = ()=>{
//     pgObj.persongroup = ''
//     hasPersonInfo.value = oldHasPersonInfo.value
// }

//渲染DOM前获取数据
// onBeforeMount(()=>{
//     reSearch()
// })


</script>

<style lang="less" scoped>
.add-first-box {
    height: 5%;
    width: 100%;
    border-bottom: #467df5 .0625rem solid;
    padding-left: 1.25rem;
    display: flex;
    justify-content: start;
    align-items: center;
}

.second-box {
    height: 95%;
    width: 100%;

    .role-box {
        height: 2.5rem;
        width: 50%;
        display: flex;
        align-items: center;

        .title-box {
            width: 70%;
            font-size: .875rem;
            color: #5e6166;
            padding-left: 1.25rem;
        }

        .icon-box {
            width: 30%;
            display: flex;
            align-items: center;
        }
    }

    .role-box:hover {
        background-color: rgba(238, 239, 241, 0.5);
    }
}

.elcb {
    flex: 1;
    display: flex;
    flex-direction: column;
    // align-items: center;
    // justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.users-box {
    height: 100%;
    width: 100%;

    .change-box {
        height: 10%;
        width: 100%;
        padding: .3125rem;
        display: flex;
        align-items: center;
    }

    .exists-box,
    .noexists-box {
        height: 45%;
        width: 100%;
        padding: .625rem;
        // background-color: aqua;
        overflow: auto;

        .check-btn {

            // display: flex;
            // justify-content:space-around ;
            .el-checkbox-button {
                margin-right: .3125rem;
                margin-bottom: .3125rem;
            }
        }
        .filter-pg-box{
            margin-bottom:.1875rem
        }
    }
}
</style>